package cmpe.swe.purcom.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import cmpe.swe.purcom.dao.UserDao;
import cmpe.swe.purcom.model.User;

@Component
public class UserService {

	@Autowired
	private UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	/**
	 * Returns a new created User object by setting its properties.
	 * 
	 * @param u
	 * @return The user object with the id generated
	 */
	public User createUser(User u) {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String pw = u.getPassword();
		u.setPassword(encoder.encode(pw));
		return userDao.createUser(u);
	}

	/**
	 * Returns a new created User object with skill attribute by setting its properties.
	 * 
	 * @param u a User object
	 * @return The new generated User object 
	 */
	public User createUserWithSkills(User u) {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String pw = u.getPassword();
		u.setPassword(encoder.encode(pw));
		userDao.createUser(u);
		userDao.attachSkillsToUser(u);
		return u;
	}

	
	/**
	 * Returns the logged in User object. If user can not logged in return null.
	 * 
	 * @param email e-mail information of the user
	 * @param password password information of the user
	 * @return a User object
	 */
	public User canLogin(String email, String password) {
		User u = userDao.getUserByEmail(email);
		if (u == null) { // no user
			return null;
		}

		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		if(encoder.matches(password, u.getPassword())){
			return u;
		}else{
			return null;
		}
	}
}
